package com.gujia.designpattern.proxysrc;


import org.apache.commons.io.FileUtils;

import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class Proxy {

    public static Object newProxyInstance(Class inter,InvocationHandler h) throws Exception{
        String rt="\r\n";
        String methodStr = "";
        for (Method method:inter.getMethods()){
            methodStr+="@Override"+rt+
                  //  methodStr+=""+rt+
                    " public void "+method.getName()+"(){"+rt+
                    " try{"+rt+
                    " Method md = "+inter.getName()+".class.getMethod(\""
                    + method.getName()+"\");"+rt+
                    " h.invoke(this,md);"+rt+
                    " }catch(Exception e){e.printStackTrace();}"+rt+
                    " }";


        }

        System.out.println("源码："+methodStr);

        String str =
                "package com.gujia.designpattern.proxysrc;"+rt+
                "import java.lang.reflect.Method;"+rt+
                "import com.gujia.designpattern.proxysrc.InvocationHandler;"+rt+
                        "public class $Proxy0 implements "+inter.getName()+"{"+rt+
                        "  public $Proxy0(InvocationHandler h){"+rt+
                        "this.h = h;"+rt+
                        "}"+rt+
                        "private InvocationHandler h;"+rt+
                        methodStr+rt+
                        "}";
        //产生代理类的java文件
        String filename = System.getProperty("user.dir")+"/src/main/java/com/gujia/designpattern/proxysrc/$Proxy0.java";
        File file = new File(filename);
        FileUtils.writeStringToFile(file,str);
        System.out.println("源码2："+str);
        //编译
        //拿到编译器
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        //文件管理者
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null,null,null);
        //获取文件
        Iterable units= fileManager.getJavaFileObjects(filename);
        //编译任务
        JavaCompiler.CompilationTask t = compiler.getTask(null,fileManager,null,null,null,units);
        t.call();

        fileManager.close();


        //load到内存中
        ClassLoader classLoader =ClassLoader.getSystemClassLoader();
        Class c = classLoader.loadClass("com.gujia.designpattern.proxysrc.$Proxy0.class");

        Constructor ctr = c.getConstructor(InvocationHandler.class);
        return ctr.newInstance(h);
    }
}
